#include "StdAfx.h"
#include "SubFormCollection.h"


CSubFormCollection::CSubFormCollection()
{
	m_nActiveForm = -1;
	m_Rect.right  = 0;
	m_Rect.top    = 0;
	m_Rect.bottom = 0;
	m_Rect.left   = 0;
	m_bCentered = false;
}

CSubFormCollection::~CSubFormCollection()
{
	// Free all sub forms on destruction
	for (int i = 0; i <=  m_Forms.GetUpperBound(); i++) {
		CDialog* pDlg = m_Forms.GetAt(i);
		pDlg->DestroyWindow();
		delete pDlg;
	}
}

//////////////////////////////////////////////////////////////////////
// Methods
//////////////////////////////////////////////////////////////////////

bool CSubFormCollection::SetActive(int ix)
{
	if (ix > m_Forms.GetUpperBound()) {
		return(false);
	}
	m_nActiveForm = ix; // make it the active one
	return(true);
}


bool CSubFormCollection::CreateSubForm(CDialog* pDlg,CWnd* pParentWnd,int iIndex)
{
	//CDialog* pDlg = new CDialog();
	ASSERT(pDlg != NULL);
	//if (pDlg == NULL) return(false);
	AddForm(pDlg,iIndex); 
	//pDlg->Create(id,pParentWnd);
	CRect r;
	int x,y;
	pDlg->GetWindowRect(&r); 
	if (m_bCentered) {
		x = m_Rect.left - r.left + ((m_Rect.Width() - r.Width()) / 2);
		y = m_Rect.top - r.top + ((m_Rect.Height() - r.Height()) / 2);
	}
	else { 
		x = m_Rect.left - r.left;
		y = m_Rect.top - r.top;
	}
	pDlg->SetWindowPos(pParentWnd,x,y, m_Rect.Width(), m_Rect.Height(), SWP_NOZORDER);
	return(true);
}

bool CSubFormCollection::ShowSubForm(int ix)
{
	ASSERT(ix <= m_Forms.GetUpperBound());
	if (ix > m_Forms.GetUpperBound()) return(false); // does not exist

	CDialog* pDlg;
	if (ix != -1) {
		if (m_nActiveForm != -1) {
			pDlg = m_Forms.GetAt(m_nActiveForm);
			ASSERT(pDlg != NULL);
			ASSERT(pDlg->m_hWnd != NULL);
			if ((pDlg == NULL) 
				||  (pDlg->m_hWnd == NULL)) return(false);
			pDlg->ShowWindow(SW_HIDE);
		}
		m_nActiveForm = ix; // this is the active one now;
	}
	else {
		if (m_nActiveForm == -1) {
			m_nActiveForm = 0;
		}
	}
	pDlg = m_Forms.GetAt(m_nActiveForm);
	ASSERT(pDlg != NULL);
	ASSERT(pDlg->m_hWnd != NULL);
	if ((pDlg == NULL) 
		||  (pDlg->m_hWnd == NULL)) return(false);
	pDlg->ShowWindow(SW_SHOW);
	pDlg->Invalidate();
	pDlg->RedrawWindow();
	return(true);
}
